package ua.edu.nuos.jeetraining2012.cms.util.mail.user;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import ua.edu.nuos.jeetraining2012.cms.service.exception.ServiceException;
import ua.edu.nuos.jeetraining2012.cms.service.exception.ServiceValidationException;
import ua.edu.nuos.jeetraining2012.cms.util.mail.UserAbstract;

import javax.validation.ValidatorFactory;
import java.io.IOException;
import java.io.StringWriter;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

public class Signup extends UserAbstract {

    private String approveURL;

    public Signup() {
        super();
    }

    public Signup(ValidatorFactory validationFactory) {
        this.validatorFactory = validationFactory;
    }

    @Override
    public String getSubject() {
        try {
            ResourceBundle i18n = getResourceBundle();
            return i18n.getString("signupSubject");
        } catch (MissingResourceException | NullPointerException e) {
            logger.error("getSubject() getResourceBundle Exception", e);
            return "Подтверждение регистрации нового пользователя";
        }
    }

    @Override
    public String getBodyMessage() {
        String md5,approveURL;
        try {
            if (this.approveURL == null)
                throw new ServiceException("Approve URL must be set");
            md5 = userService.getMd5(userEntity.getEmail());
            approveURL = String.format("%s?id=%s&email=%s",this.approveURL,URLEncoder.encode(md5,"UTF-8"),URLEncoder.encode(userEntity.getEmail(),"UTF-8"));
            Map<String, Object> datamodel = new HashMap<>();
            ResourceBundle i18n = getResourceBundle();
            datamodel.put("signupBody", i18n.getString("signupBody"));
            datamodel.put("approveURL",String.format("<a href=\"%1$s\">%1$s</a>",approveURL));
            Configuration cfg = getTemplateConfig();
            Template template = cfg.getTemplate("signup.ftl");
            StringWriter writer = new StringWriter();
            template.process(datamodel, writer);
            return writer.toString();
        } catch (IOException | TemplateException |
                MissingResourceException | NullPointerException |
                ServiceValidationException | ServiceException e) {
            logger.error("getBodyMessage() Exception", e);
        }
        return null;
    }


    /**
     * Set contextPath to be used for URL construction
     *
     * @param approveURL specify contextPath of the request for link construction
     */
    public void setApproveURL(String approveURL) {
        if ((approveURL == null) || (!approveURL.startsWith("http://")))
            throw new IllegalArgumentException("Approve url can't be null and must start with http://");

        this.approveURL = approveURL;
    }
}
